<?php
/**
 * Created by PhpStorm.
 * User: 731633799@qq.com
 * Date: 2019/6/4
 * Time: 12:30
 */

namespace addons\weapp\controller;

use think\addons\Controller;
use think\Model;

class Common extends Controller
{
    protected $layout = 'default';
    protected $seo_title = '';
    protected $seo_keywords = '';
    protected $cat_info = [];
    protected $cat_id = null;
    protected $menu = [];
    protected $nav = [];

    /**
     * 首页
     */

    public function _initialize()
    {
        parent::_initialize();
		
		//变量获取
		//变量类型方法('变量名/变量修饰符','默认值','过滤方法') //param方法
		//设置$cat_id为0
		$this->cat_id = $this->request->param("cat", 0, 'int');
		//dump($this->cat_id);
		
        $this->menu();
        $weapp = get_addon_config("weapp");
        $banner = $weapp["banner"];
		//dump($banner);
        $this->assign("banner", explode(",", $banner));
        $this->assign("app", $this->app());
        $this->request->action() != "show" && $this->assign_web_info(); //action()助手函数
		
    }

    public function menu()
    {
        $this->nav = ["首页"];
        $controller = $this->request->controller();
        $cat_id = $this->cat_id;
		
        $menu = [
            ['url' => "weapp/index", "title" => "网站首页"],
            ['url' => "weapp/about", "title" => "关于我们"],
            [
                'url'    => "weapp/product",
                "title"  => "产品展示",
                "catkey" => "productcat_id",
                "sub"    => collection($this->product_cat())->toArray()
            ],
            [
                'url'    => "weapp/cases",
                "title"  => "案例展示",
                "catkey" => "casescat_id",
                "sub"    => collection($this->cases_cat())->toArray()
            ],
            ['url' => "weapp/brand", "title" => "品牌列表"],
            ['url' => "weapp/contact", "title" => "联系我们"],
        ];
		// $value = function ($item) use ($controller,$cat_id){};
		// print_r('<pre>');
		// print_r($value);
		// print_r('</pre>');
		
		
		//array_map(myfunction,array1,array2) 函数将用户自定义函数作用到数组中的每个值上，并返回用户自定义函数作用后的带有新的值的数组
		//myfunction	必需。用户自定义函数的名称，或者是 null。
		//array1	必需。规定数组。array2	可选。规定数组。
        $menu = array_map(function ($item) use ($controller, $cat_id) {
			//dump($item);//处理前的$item
			
			//当前导航url处理
            if ($item['url'] == sprintf("weapp/%s", $controller)) {//sprintf() 函数把格式化的字符串写入一个变量中。
				//dump($item['url']);
				
				//赋值当前url样式active
                $item['active'] = "active";
				
				//array_push() 函数向数组尾部插入一个或多个元素
				//sprintf(format,arg1,arg2,arg++) //%s - 字符串格式
				//参数将被插入到主字符串中的百分号（%）符号处。该函数是逐步执行的。在第一个 % 符号处，插入 arg1，在第二个 % 符号处，插入 arg2，依此类推
                array_push($this->nav, sprintf("<a href='%s'>%s</a>", addon_url($item['url']), $item['title']));//当前导航url
				//dump($this->nav);
				
            } else {
                $item['active'] = "";
            }
			
			
			//子类导航url处理
			/**start*/
            if (isset($item['sub'])) {
				$sub = $item['sub'];
				//dump($sub);
                unset($item['sub']);
                foreach ($sub as $key => $v) {
					//dump($v);//dump($v['id']);//dump($v['name']);
					
                    $temp_sub = [
                        "cat_id" => $v['id'],
                        "title"  => $v['name'],
						"url"    => addon_url($item['url'], ["cat" => $v['id']]),//addon_url()函数方法
                        "active" => ((isset($item['active']) && !empty($item['active']) && $cat_id == $v['id']) ? "active" : '')
                    ];
					//dump($temp_sub);
					//$temp_sub赋值给子类
                    $item['sub'][$v['id']] = $temp_sub;
					//dump($item['sub']);
					//dump($item['sub'][$v['id']]);
					
					
					//将子类导航url添加到数组
                    if (isset($temp_sub['active']) && $temp_sub['active'] == 'active') {
                        array_push($this->nav, sprintf("<a href='%s'>%s</a>", $temp_sub['url'], $temp_sub['title']));
						//dump($this->nav);
                    }
                }
            }
			/**end*/
			
			
			//dump($item);//处理后的$item
			
            $item['url'] = addon_url($item['url']);
		    //dump($item['url']);
			
			if ($item['active'] == "active") {
                $this->cat_info = $item;
				//dump($this->cat_info['sub']);
				
                $this->seo_title = $item['title'];
            }
            return $item;
        }, $menu);
		
        $this->menu = $menu;
		//dump($menu);
        return $menu;
    }

    protected function assign_web_info()
    {
        $this->assign(
            "seo_title",
            empty($this->seo_title) ? $this->app()['title'] : $this->seo_title . "-" . $this->app()['title']
        );
        $this->menu();
        $this->assign("seo_keywords", empty($this->seo_keywords) ? $this->app()['seo_keywords'] : $this->seo_keywords);
        $this->assign("menu", $this->menu);
        $this->assign("cat_info", $this->cat_info);
        $this->assign("nav_button", implode(" >> ", $this->nav));
    }

    public function app()
    {
        $site = get_addon_config("weapp");
        return [
            'title'        => $site['title'],
            "phone"        => $site['phone'],
            "address"      => $site['address'],
            "logo"         => $site['logo'],
            "icp"          => $site['icp'],
            "email"        => $site['company_email'],
            'seo_keywords' => $site['seo_keywords'],
        ];
    }

    public function product_cat()
    {
        $db = model("admin/WeappProductcat");
        $data = $db->order("weigh desc,id desc")->field("id,name")->cache(true, 24 * 60 * 60)->select();
        return $data;
    }

    public function cases_cat()
    {
        $db = model("admin/WeappCasescat");
        $data = $db->order("weigh desc,id desc")->field("id,name")->cache(true, 24 * 60 * 60)->select();
        return $data;
    }

    public function next(Model $db, $id)//定义Model?  如 $db = model("当前模型"); 
    {
		$conteoller = $this->request->controller();
		//dump($conteoller);
        $data = $db->where(['id' => ["<", $id]])->order("id desc")->find();//查找的id小于当前传入的$id，则有上一篇
		//dump($data);
        return $data ? sprintf(
            " <a href='%s'>%s</a>",
            addon_url("weapp/$conteoller/show", ['id' => $data->id]),
            $data->name
        ) : "没有了";
    }

    public function pre(Model $db, $id)
    {
        $conteoller = $this->request->controller();
        $data = $db->where(['id' => [">", $id]])->order("id asc")->find();
		//dump($data);
        return $data ? sprintf(
            " <a href='%s'>%s</a>",
            addon_url("weapp/$conteoller/show", ['id' => $data->id]),
            $data->name
        ) : "没有了";
    }


    public function show()
    {
        $cat = $this->request->controller();
        $cat = ucfirst($cat);//ucfirst() 函数把字符串中的首字符转换为大写
		//dump($cat);
        $db = model("admin/Weapp$cat");//后端admin的模型
		//dump($db);
        $data = $db->find($this->request->param("id")); //单条数据
		//dump($data);
		
		//dump($this->cat_info);
	
		
        if ($data && isset($this->cat_info['catkey']) && isset($data[$this->cat_info['catkey']])) {
			
			//这行代码就添加了高亮样式
            $this->cat_id = $data[$this->cat_info['catkey']]; //例 $cat_id = $data['productcat_id']
			//dump($data[$this->cat_info['catkey']]);
			
			/* 貌似不需要的代码 */
			/* if (isset($this->cat_info['sub']) && isset($this->cat_info['sub'][$this->cat_id]['active'])) {
				$this->cat_info['sub'][$this->cat_id]['active'] = "active";
            }; */
			
        }
        $this->seo_title = $data->name;
        $this->assign_web_info();
        $this->assign("data", $data);
        $this->assign("next", $this->next($db, $this->request->param("id")));
        $this->assign("pre", $this->pre($db, $this->request->param("id")));
        return $this->view->fetch("show/index");
    }
}
